package com.java.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class Reflect04_User {
    public static void main(String[] args) throws Exception {
        Class userClass = User.class ;
        // 获取公共字段
        Field[] pubArr = userClass.getFields() ;
        printField(pubArr);
        // 获取全部字段
        Field[] fieldArr = userClass.getDeclaredFields() ;
        printField(fieldArr);
        // 获取指定字段
        Field emailField = userClass.getField("email") ;
        Field nameField = userClass.getDeclaredField("name") ;
        printField(new Field[]{emailField,nameField});
        // 创建对象并操作属性
        Object userObj = userClass.newInstance() ;
        nameField.setAccessible(Boolean.TRUE);
        nameField.set(userObj,"world");
        emailField.set(userObj,"test@email.com");
        System.out.println("userObj:"+userObj);
    }
    /**
     * 打印成员变量信息
     */
    public static void printField (Field[] fields){
        for (Field field : fields){
            System.out.println("声明："+field);
            UserAnno userAnno = field.getAnnotation(UserAnno.class) ;
            System.out.println("注解："+userAnno.desc());
            String fieldName = field.getName() ;
            System.out.println("名称："+fieldName);
            Type type = field.getGenericType() ;
            System.out.println("类型："+type);
        }
        System.out.println("================================");
    }
}
